package com.pig4cloud.pig.djjk.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.djjk.domain.po.DeviceInfo;
import com.pig4cloud.pig.djjk.entity.DeviceEntity;
import com.pig4cloud.pig.djjk.service.DeviceService;
import com.pig4cloud.pig.djjk.service.HikService;
import com.pig4cloud.pig.djjk.service.wd.WdboxService;
import com.pig4cloud.plugin.excel.annotation.RequestExcel;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备信息
 *
 * @author wd
 * @date 2025-06-08 20:17:42
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/device" )
@Tag(description = "device" , name = "设备信息管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class DeviceController {

    private final  DeviceService deviceService;
	private final HikService hikService;
    @Value("${wd.client.url}")
    private String clientUrl;
    /**
     * 分页查询
     * @param page 分页对象
     * @param device 设备信息
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('djjk_device_view')" )
    public R getDevicePage(@ParameterObject Page page, @ParameterObject DeviceEntity device) {
        LambdaQueryWrapper<DeviceEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(device.getDeptId()!=null,DeviceEntity::getDeptId,device.getDeptId());
		wrapper.like(StrUtil.isNotBlank(device.getDeviceName()),DeviceEntity::getDeviceName,device.getDeviceName());
		wrapper.like(StrUtil.isNotBlank(device.getDeviceCode()),DeviceEntity::getDeviceCode,device.getDeviceCode());
		wrapper.eq(StrUtil.isNotBlank(device.getLadderModel()),DeviceEntity::getLadderModel,device.getLadderModel());
		Page page1 = deviceService.page(page, wrapper);
		return R.ok(page1);
    }


    /**
     * 通过条件查询设备信息
     * @param device 查询条件
     * @return R  对象列表
     */
    @Operation(summary = "通过条件查询" , description = "通过条件查询对象" )
    @GetMapping("/details" )
    @PreAuthorize("@pms.hasPermission('djjk_device_view')" )
    public R getDetails(@ParameterObject DeviceEntity device) {
        return R.ok(deviceService.list(Wrappers.query(device)));
    }

    /**
     * 新增设备信息
     * @param device 设备信息
     * @return R
     */
    @Operation(summary = "新增设备信息" , description = "新增设备信息" )
    @SysLog("新增设备信息" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('djjk_device_add')" )
    public R save(@RequestBody DeviceEntity device) {
        boolean save = deviceService.save(device);
        if(save){
            try {
                HttpUtil.post(clientUrl+"/hik/device/add", JSON.toJSONString(device));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return R.ok(save);
    }

    /**
     * 修改设备信息
     * @param device 设备信息
     * @return R
     */
    @Operation(summary = "修改设备信息" , description = "修改设备信息" )
    @SysLog("修改设备信息" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('djjk_device_edit')" )
    public R updateById(@RequestBody DeviceEntity device) {
        boolean upd = deviceService.updateById(device);
        if(upd){
            try {
//				if(!StrUtil.equals(clientUrl,"http://127.0.0.1")) {
//					HttpUtil.post(clientUrl+"/hik/device/add", JSON.toJSONString(device));
//					if(device.getLadderModel().equals("1")){
//						HttpUtil.get(clientUrl+"/hik/trace/auto?deviceCode="+device.getDeviceCode());
//					}else{
//						HttpUtil.get(clientUrl+"/hik/trace/manual?deviceCode="+device.getDeviceCode());
//					}
//				}
				DeviceInfo deviceInfo = new DeviceInfo();
				deviceInfo.setDeviceId(device.getDeviceCode());
				deviceInfo.setDeviceIP(device.getDeviceIp());
				deviceInfo.setDeviceName(device.getDeviceName());
				deviceInfo.setDeviceAccount(device.getDeviceAccount());
				deviceInfo.setDevicePwd(device.getDevicePwd());
				deviceInfo.setBoardRight(device.getDevicePosition().equals("1"));
				deviceInfo.setDevicePort(Convert.toInt(device.getDevicePort()));
				deviceInfo.setAutoLadder(device.getLadderModel().equals("1"));
				WdboxService.deviceInfoMap.put(deviceInfo.getDeviceId(),deviceInfo);

				if(device.getLadderModel().equals("1")){
					if(WdboxService.deviceInfoMap.containsKey(device.getDeviceCode())){
						WdboxService.deviceInfoMap.get(device.getDeviceCode()).setAutoLadder(true);
						log.info("镜头自动跟踪梯子{}",device.getDeviceCode());
					}else{
						log.info("镜头自动跟踪梯子,设备未注册{}",device.getDeviceCode());
					}
				}else{
					if(WdboxService.deviceInfoMap.containsKey(device.getDeviceCode())){
						WdboxService.deviceInfoMap.get(device.getDeviceCode()).setAutoLadder(false);
						log.info("镜头自动跟踪梯子关闭{}",device.getDeviceCode());
					}else{
						log.info("镜头自动跟踪梯子关闭,设备未注册{}",device.getDeviceCode());
					}
				}
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return R.ok(upd);
    }

    /**
     * 通过id删除设备信息
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除设备信息" , description = "通过id删除设备信息" )
    @SysLog("通过id删除设备信息" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('djjk_device_del')" )
    public R removeById(@RequestBody Long[] ids) {
        List<DeviceEntity> deviceEntities = deviceService.listByIds(CollUtil.toList(ids));
//        List<String> collect = deviceEntities.stream().map(DeviceEntity::getDeviceCode).collect(Collectors.toList());
        boolean dels = deviceService.removeBatchByIds(CollUtil.toList(ids));
        if(dels){
            try {
//                HttpUtil.get(clientUrl+"/hik/device/del?ids="+StrUtil.join(",",collect));
				if(ArrayUtil.isNotEmpty(ids)){
					for (Long id : ids) {
						WdboxService.deviceInfoMap.remove(id);
					}
				}
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return R.ok(dels);
    }


    /**
     * 导出excel 表格
     * @param device 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('djjk_device_export')" )
    public List<DeviceEntity> exportExcel(DeviceEntity device,Long[] ids) {
        return deviceService.list(Wrappers.lambdaQuery(device).in(ArrayUtil.isNotEmpty(ids), DeviceEntity::getId, ids));
    }

    /**
     * 导入excel 表
     * @param deviceList 对象实体列表
     * @param bindingResult 错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @PreAuthorize("@pms.hasPermission('djjk_device_export')" )
    public R importExcel(@RequestExcel List<DeviceEntity> deviceList, BindingResult bindingResult) {
        return R.ok(deviceService.saveBatch(deviceList));
    }

    @Inner(value = false)
    @RequestMapping("/list" )
    public R getDeviceList() {
        return R.ok(deviceService.list(new LambdaQueryWrapper<DeviceEntity>().isNotNull(DeviceEntity::getDeviceIp)
				.isNotNull(DeviceEntity::getDeviceAccount)
				.isNotNull(DeviceEntity::getDevicePwd)
		));
    }


	@RequestMapping("/getPreviewUrl")
	@PreAuthorize("@pms.hasPermission('djjk_device_view')" )
	public R getPreviewUrl(String code) {
		return R.ok(hikService.previewURLs(code,"hls"));
	}

	@RequestMapping("/getRTSPUrl")
	@PreAuthorize("@pms.hasPermission('djjk_device_edit')" )
	public R getRTSPUrl(String code) {
		return R.ok(hikService.previewURLs(code,"rtmp"));
	}
}
